from copy import deepcopy

from PIL import ImageFilter, ImageFont, ImageDraw, Image
from io import BytesIO
from config import WIDTH, HEIGHT, REQUEST_FORMAT_CODE
from random import randint

font = ImageFont.truetype(font='C:\WINDOWS\Fonts\SIMYOU.TTF', size=25)


def create_img(word: list):
    img = Image.new(mode='RGB', size=(WIDTH, HEIGHT), color=(210, 210, 210))
    draw = ImageDraw.Draw(img, mode='RGB')
    for i in range(len(word)):
        draw.text([i * 50 + 20, randint(0, 25)], word[i], font=font, fill=rndColor())

    # 干扰
    interference(draw)

    # 保存到缓存中
    item = BytesIO()
    img.save(item, format='png')
    return item


def interference(draw):
    # 写干扰圆圈
    for i in range(40):
        draw.point([randint(0, WIDTH), randint(0, HEIGHT)], fill=rndColor())
        x = randint(0, WIDTH)
        y = randint(0, HEIGHT)
        draw.arc((x, y, x + 4, y + 4), 0, 90, fill=rndColor())

    # 画干扰线
    for i in range(5):
        x1 = randint(0, WIDTH)
        y1 = randint(0, HEIGHT)
        x2 = randint(0, WIDTH)
        y2 = randint(0, HEIGHT)

        draw.line((x1, y1, x2, y2), fill=rndColor())


def rndColor():
    """
    生成随机颜色
    :return:
    """
    return (randint(0, 255), randint(10, 255), randint(64, 255))

def my_route(code, data={}):
    return {'code': code, 'msg': REQUEST_FORMAT_CODE.get(code, 407), 'data': data}


def item2dict(item, filter=[], choose=[]):
    if isinstance(item, list):
        datas = []
        for i in item:
            datas.append(item2dict(i), filter, choose)
        return datas

    data = deepcopy(item.__dict__)
    data.pop('_sa_instance_state')
    if choose:
        return {k: data.get(k) for k in choose}
    for i in filter:
        data.pop(i)
    return data
